const express = require('express')
const { WorkOrder, Material } = require('../models')
const router = express.Router()

// 获取实时数据
router.get('/data', async (req, res) => {
  try {
    // 统计信息
    const inventoryCount = await Material.count()
    const workOrderCount = await WorkOrder.count({ where: { status: 'running' } })
    
    // 今日产量
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const todayWorkOrders = await WorkOrder.findAll({
      where: {
        createdAt: {
          [Op.gte]: today
        },
        status: 'completed'
      }
    })
    const todayProduction = todayWorkOrders.reduce((sum, order) => {
      return sum + parseFloat(order.actualQuantity || 0)
    }, 0)
    
    // 异常告警（简化处理）
    const alertCount = await WorkOrder.count({
      where: {
        status: 'stopped'
      }
    })
    
    // 最近工单
    const recentWorkOrders = await WorkOrder.findAll({
      include: [
        { model: Material, as: 'product', attributes: ['name', 'code'] }
      ],
      order: [['createdAt', 'DESC']],
      limit: 10
    })
    
    res.json({
      stats: {
        inventoryCount,
        workOrderCount,
        todayProduction,
        alertCount
      },
      recentWorkOrders
    })
  } catch (error) {
    console.error('获取实时数据错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

module.exports = router
